/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/graph/core/optimize/schedule/node_optimize_scheduler.h"

#include "infra/base/assertion.h"
#include "infra/base/securestl.h"

#include "framework/graph/core/node/node.h"
#include "framework/graph/core/node/node_spec.h"
#include "framework/graph/core/node/node_visitor.h"

#include "framework/graph/core/cgraph/compute_graph.h"
#include "framework/graph/core/cgraph/graph_list_walker.h"
#include "framework/graph/core/cgraph/graph_listener.h"

#include "framework/graph/core/optimize/schedule/node_pass_list.h"

namespace hiai {
namespace {
class NodeOptimizeSchedulerImpl : public NodeOptimizeScheduler, private ge::GraphListener {
public:
    NodeOptimizeSchedulerImpl(NodePassList& passList, size_t maxOptimizeLoopCount)
        : passList_(passList), maxOptimizeLoopCount_(maxOptimizeLoopCount)
    {
    }
    ~NodeOptimizeSchedulerImpl() override = default;

private:
    Status Schedule(ge::ComputeGraph& graph) override
    {
        ge::AutoGraphListener optimizerListener(graph.ROLE(GraphNotifier), *this);

        // filter attention nodes
        (void)graph.ROLE(GraphListWalker).WalkAllNodes([this](ge::Node& node) {
            if (passList_.Attention(node.ROLE(NodeSpec).Type())) {
                optimizeNodes_.emplace(&node, true);
            }
            return SUCCESS;
        });

        return OptimizeRepeated(graph);
    }

private:
    void OnAddNode(ge::Node& node) override
    {
        const std::string& type = node.ROLE(NodeSpec).Type();
        if (passList_.Attention(type)) {
            updateNodes_.emplace(&node, true);
        }
    }

    void OnDelNode(const ge::Node& node) override
    {
        ge::Node* n = const_cast<ge::Node*>(&node);
        optimizeNodes_[n] = false;

        auto iter = updateNodes_.find(n);
        if (iter != updateNodes_.cend()) {
            updateNodes_.erase(iter);
        }
    }

private:
    Status OptimizeRepeated(ge::ComputeGraph& graph)
    {
        for (size_t i = 0; i < maxOptimizeLoopCount_; i++) {
            auto status = Optimize(graph);
            if (status == OptimizeStatus::OPTIMIZE_FAILED) {
                return FAILURE;
            } else if (status == OptimizeStatus::OPTIMIZE_NOT_CHANGED) {
                return SUCCESS;
            }
            UpdateNodes();
        }
        return SUCCESS;
    }

    OptimizeStatus Optimize(ge::ComputeGraph& graph)
    {
        auto allPassStatus = OptimizeStatus::OPTIMIZE_NOT_CHANGED;
        for (const auto& optimizeNode : optimizeNodes_) {
            auto passStatus = passList_.Optimize(
                *(optimizeNode.first), graph, [this](ge::Node& node) { return optimizeNodes_[&node]; });
            if (passStatus == OptimizeStatus::OPTIMIZE_FAILED) {
                return OptimizeStatus::OPTIMIZE_FAILED;
            } else if (passStatus == OptimizeStatus::OPTIMIZE_CHANGED) {
                allPassStatus = OptimizeStatus::OPTIMIZE_CHANGED;
            }
        }

        return allPassStatus;
    }

    void UpdateNodes()
    {
        RemoveInvalidNodes();
        MergeUpdateNodes();
    }

    void RemoveInvalidNodes()
    {
        for (auto iter = optimizeNodes_.cbegin(); iter != optimizeNodes_.cend();) {
            if (!iter->second) {
                iter = optimizeNodes_.erase(iter);
            } else {
                iter++;
            }
        }
    }

    void MergeUpdateNodes()
    {
        for (const auto& node : updateNodes_) {
            optimizeNodes_.insert(node);
        }
        updateNodes_.clear();
    }

    bool ValidateNode(ge::Node* node)
    {
        return optimizeNodes_[node];
    }

private:
    NodePassList& passList_;
    size_t maxOptimizeLoopCount_;
    std::map<ge::Node*, bool> optimizeNodes_;
    std::map<ge::Node*, bool> updateNodes_;
};
} // namespace

std::unique_ptr<NodeOptimizeScheduler> NodeOptimizeScheduler::Make(NodePassList& passList, size_t maxOptimizeLoopCount)
{
    HIAI_EXPECT_TRUE_R(maxOptimizeLoopCount <= 3, nullptr);

    return make_unique_nothrow<NodeOptimizeSchedulerImpl>(passList, maxOptimizeLoopCount);
}
} // namespace hiai